package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.advice.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.ApartmentInfoMapper;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {
    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;
    @Autowired
    private ProvinceInfoService provinceInfoService;
    @Autowired
    private DistrictInfoService districtInfoService;
    @Autowired
    private CityInfoService cityInfoService;
    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private ApartmentFacilityService apartmentFacilityService;
    @Autowired
    private ApartmentLabelService apartmentLabelService;
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;
    @Autowired
    private RoomInfoService roomInfoService;


    /**
     * 根据项目ID和类型删除相关子表记录
     * 此方法旨在清理与特定项目相关的所有子表数据，确保数据一致性
     *
     * @param id 项目ID，用于定位要删除的记录
     * @param type 项目类型，与ID一起用于精确查找
     */
    public void delectSonTable(Long id, ItemType type) {
       // 创建GraphInfo表的查询包装器，用于条件查询
       LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper
               =new LambdaQueryWrapper<>();
       // 设置查询条件：项ID和项类型匹配给定值
       graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId,id)
                       .eq(GraphInfo::getItemType,type);
       // 执行删除操作，移除匹配的GraphInfo记录
       graphInfoService.remove(graphInfoLambdaQueryWrapper);

       // 创建ApartmentFacility表的查询包装器
       LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper
               = new LambdaQueryWrapper<>();
       // 设置查询条件：公寓ID匹配给定值
       apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId, id);
       // 执行删除操作，移除匹配的ApartmentFacility记录
       apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);

       // 创建ApartmentLabel表的查询包装器
       LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper
               = new LambdaQueryWrapper<>();
       // 设置查询条件：公寓ID匹配给定值
       apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId, id);
       // 执行删除操作，移除匹配的ApartmentLabel记录
       apartmentLabelService.remove(apartmentLabelLambdaQueryWrapper);

       // 创建ApartmentFeeValue表的查询包装器
       LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper
               = new LambdaQueryWrapper<>();
       // 设置查询条件：公寓ID匹配给定值
       apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId, id);
       // 执行删除操作，移除匹配的ApartmentFeeValue记录
       apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);
    }


    @Override
    public void customPage(Page<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        apartmentInfoMapper.customSelsectAll(page, queryVo);
    }

    /**
     * 保存或更新公寓提交信息
     *
     * 当公寓信息已存在时，先删除原有相关子表数据，然后根据新的提交信息更新或保存公寓信息及其关联信息
     *
     * @param apartmentSubmitVo 公寓提交信息对象，包含公寓的基本信息、图片、设施、费用等
     */
    @Override
    public void customSave(ApartmentSubmitVo apartmentSubmitVo) {
        // 判断公寓信息是否已存在
        boolean exits = apartmentSubmitVo.getId() != null;

        // 根据省、市、区ID获取对应的名称，并设置到公寓提交对象中
        ProvinceInfo provinceInfo = provinceInfoService.getById(apartmentSubmitVo.getProvinceId());
        CityInfo cityInfo = cityInfoService.getById(apartmentSubmitVo.getCityId());
        DistrictInfo districtInfo = districtInfoService.getById(apartmentSubmitVo.getDistrictId());
        apartmentSubmitVo.setProvinceName(provinceInfo.getName());
        apartmentSubmitVo.setCityName(cityInfo.getName());
        apartmentSubmitVo.setDistrictName(districtInfo.getName());

        // 保存或更新公寓提交信息
        saveOrUpdate(apartmentSubmitVo);

        // 如果公寓信息已存在，删除原有相关子表数据
        if (exits) {
            delectSonTable(apartmentSubmitVo.getId(), ItemType.APARTMENT);
        }

        // 处理公寓图片信息，如果存在，则批量保存
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        if(!CollectionUtils.isEmpty(graphVoList)){
            List<GraphInfo> graphInfoList=new ArrayList<>(graphVoList.size());
            for (GraphVo graphVo : graphVoList) {
                GraphInfo graphInfo=new GraphInfo();
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfo.setItemId(apartmentSubmitVo.getId());
                graphInfo.setItemType(ItemType.APARTMENT);
                graphInfoList.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfoList);
        }

        // 处理公寓设施信息，如果存在，则批量保存
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        if(!CollectionUtils.isEmpty(facilityInfoIds)){
            List<ApartmentFacility>apartmentFacilityList=new ArrayList<>(facilityInfoIds.size());
            for (Long facilityInfoId : facilityInfoIds) {
                ApartmentFacility apartmentFacility = ApartmentFacility.builder()
                        .apartmentId(apartmentSubmitVo.getId())
                        .facilityId(facilityInfoId).build();
                apartmentFacilityList.add(apartmentFacility);
            }
            apartmentFacilityService.saveBatch(apartmentFacilityList);
        }

        // 处理公寓费用信息，如果存在，则批量保存
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        if(!CollectionUtils.isEmpty(feeValueIds)){
            List<ApartmentFeeValue>apartmentFeeValueList
                    =new ArrayList<>(feeValueIds.size());
            for (Long feeValueId : feeValueIds) {
                ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder()
                        .apartmentId(apartmentSubmitVo.getId())
                        .feeValueId(feeValueId).build();
                apartmentFeeValueList.add(apartmentFeeValue);
            }
            apartmentFeeValueService.saveBatch(apartmentFeeValueList);
        }

        // 处理公寓标签信息，如果存在，则批量保存
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        if(!CollectionUtils.isEmpty(labelIds)){
            List<ApartmentLabel>apartmentLabelList
                    =new ArrayList<>(labelIds.size());
            for (Long labelId : labelIds) {
                ApartmentLabel apartmentLabel = ApartmentLabel.builder()
                        .apartmentId(apartmentSubmitVo.getId())
                        .labelId(labelId).build();
                apartmentLabelList.add(apartmentLabel);
            }
            apartmentLabelService.saveBatch(apartmentLabelList);
        }
    }

    /**
     * 根据ID自定义删除方法
     * 在删除前检查是否有关联的房间信息，如果有，则抛出异常
     * 这是为了维护数据的完整性，避免出现孤立的房间信息
     *
     * @param id 要删除的公寓ID
     * @throws LeaseException 如果尝试删除的公寓有关联的房间信息时抛出异常
     */
    @Override
    public void customRemoveById(Long id) {
        // 创建一个Lambda查询包装器，用于查询房间信息
        LambdaQueryWrapper<RoomInfo> roomInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 设置查询条件：房间信息的公寓ID等于传入的ID
        roomInfoLambdaQueryWrapper.eq(RoomInfo::getApartmentId, id);
        // 检查是否有匹配的房间信息
        if (roomInfoService.count(roomInfoLambdaQueryWrapper) > 0) {
            // 如果存在关联的房间信息，抛出异常，表示不能删除该公寓
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }
        // 调用方法删除子表中的关联数据
        delectSonTable(id, ItemType.APARTMENT);
        // 调用方法按ID删除公寓信息
        removeById(id);
    }

    @Override
    public ApartmentDetailVo customGetById(Long id) {
        return apartmentInfoMapper.customSelectById(id);
    }
}




